﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControllerLayer.Reports;
using ControllerLayer.MainView;
using ViewLayer.RejectedStudies;
using MedicalDictationView;
using ModelLayer.Login;
using ViewLayer.MainView;
using ControllerLayer.Login;
using ControllerLayer.Impersonator;
using System.Diagnostics;
using System.IO;
using System.Configuration;

namespace ViewLayer.Studies
{
    public partial class StudiesViewControl : UserControl
    {
        private bool isNewDictationFlag;
        Login.LoginView login2;
        private int typeReport;
        User user = User.Instance;

        public StudiesViewControl( )
        {     
            typeReport = 0; //1 sin dictados
            InitializeComponent();

            DataTable radiologists = ReportsController.GetRadiologists();
            for (int i = 0; i < radiologists.Rows.Count; i++)
            {
                this.comboBoxUser.Items.Add(radiologists.Rows[i].ItemArray[1].ToString());
            }
            comboBoxUser.Text = user.getName();

            this.staff_TableAdapter.Fill(this.externalPractitionerDataSet.Staff_);
            try
            {
                this.visit_TableAdapter.Fill(this.visitSummaryDataSet.Visit_, MainViewController.currentAccessionNumber);

                this.reportPart_TableAdapter.Fill(this.reportDataSet.ReportPart_, ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));
                this.reportPartExtendedProperty_TableAdapter.Fill(this.reportDataSet.ReportPartExtendedProperty_);

                this.reportPart_TableAdapter1.FillBy(this.reportChildDataSet.ReportPart_, new Guid(reportPart_DataGridView[0,0].Value.ToString()), Int32.Parse(reportPart_DataGridView[2, 0].Value.ToString()));
                this.reportPartExtendedProperty_TableAdapter1.Fill(this.reportChildDataSet.ReportPartExtendedProperty_);
            }
            catch (System.Exception ex)
            {}
        }

        private void reportPart_DataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                this.reportPart_TableAdapter1.FillBy(this.reportChildDataSet.ReportPart_, new Guid(reportPart_DataGridView[0, 0].Value.ToString()), Int32.Parse(reportPart_DataGridView[2, e.RowIndex].Value.ToString()));
                this.reportPartExtendedProperty_TableAdapter1.Fill(this.reportChildDataSet.ReportPartExtendedProperty_);
            }
        }

        private void buttonAddDictations_Click(object sender, EventArgs e)
        {
                typeReport = 0;

                if (ReportsController.dictationIU == null)
                    ReportsController.dictationIU = new MainIU();

                ReportsController.dictationIU.Show();
                ReportsController.dictationIU.dictationClosed += new MainIU.CloseHandler(dictationIU_dictationClosed);
                DateTime time = DateTime.Now;
                string[] myParameters = new string[] { "", "0", MainViewController.currentPID, MainViewController.currentPatientName, MainViewController.currentAccessionNumber, MainViewController.selectedProcedureTypeName, user.getFamilyName() + ", " + user.getGivenName(), time.ToString() };
                ReportsController.dictationIU.LoadDictation(myParameters, true);
                this.isNewDictationFlag = true;
        }

        private void reportPart_DataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (ReportsController.dictationIU == null)
                    ReportsController.dictationIU = new MainIU();

                ReportsController.dictationIU.Show();
                ReportsController.dictationIU.dictationClosed += new MainIU.CloseHandler(dictationIU_dictationClosed);
                String dPath = ReportsController.GetPathOfReportPartOid(new Guid(reportPart_DataGridView[1, e.RowIndex].Value.ToString()));

                if (this.reportPart_DataGridView[4, e.RowIndex].Value.ToString() == "En progreso")
                {
                    string[] myParameters = new string[] { dPath, "0", MainViewController.currentPID, MainViewController.currentPatientName, MainViewController.currentAccessionNumber, MainViewController.selectedProcedureTypeName, reportPart_DataGridView[14, e.RowIndex].Value.ToString(), reportPart_DataGridView[5, e.RowIndex].Value.ToString() };
                    ReportsController.dictationIU.LoadDictation(myParameters, false);
                    this.isNewDictationFlag = false;
                }
                else
                {
                    string[] myParameters = new string[] { dPath, "1", MainViewController.currentPID, MainViewController.currentPatientName, MainViewController.currentAccessionNumber, MainViewController.selectedProcedureTypeName, reportPart_DataGridView[14, e.RowIndex].Value.ToString(), reportPart_DataGridView[5, e.RowIndex].Value.ToString() };
                    ReportsController.dictationIU.LoadDictation(myParameters, false);
                    this.isNewDictationFlag = false;
                }
            }
        }

        void dictationIU_dictationClosed(object sender, CloseArgs args)
        {
            if (this.isNewDictationFlag)
            {
                if (!(args.FilePath == ""))
                {
                    ReportsController.InsertNewDictation(MainViewController.currentAccessionNumber, args.FilePath, user.getStaffOID().ToString());

                    if (args.ToTranscribe)
                    {
                        RefreshDictations(ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));
                        ReportsController.UpdateDictation(new Guid(reportPart_DataGridView[1, 0].Value.ToString()), "AT");
                    }
                }
            }
            else
            {
                if (args.ToTranscribe)
                {
                    ReportsController.UpdateDictation(new Guid(reportPart_DataGridView[1, 0].Value.ToString()), "AT");
                }
            }

            if (ReportsController.dictationIU != null)
            {
                ReportsController.dictationIU.Dispose();
                ReportsController.dictationIU = null;
            }

            RefreshDictations(ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));

            this.ParentForm.BringToFront();
        }

        #region DataGrid CellContentClick

        private void reportPart_DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == (this.reportPart_DataGridView.Columns.Count - 1))
            {
                if (MessageBox.Show("Está seguro que desea eliminar este dictado?", "Información", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    ReportsController.DeleteDictation(new Guid(this.reportPart_DataGridView[1, e.RowIndex].Value.ToString()), "X", new Guid(this.reportPart_DataGridView[0, e.RowIndex].Value.ToString()), int.Parse(this.reportPart_DataGridView[2, e.RowIndex].Value.ToString()));
                //refrescar el datagridview del los dictados
                RefreshDictations(new Guid(this.reportPart_DataGridView[0, e.RowIndex].Value.ToString()));

                //refrescar el datagridview del los informes
                if (reportPart_DataGridView1.RowCount != 0)
                {
                    if (reportPart_DataGridView.RowCount != 0)
                    {
                        this.reportPart_TableAdapter1.FillBy(this.reportChildDataSet.ReportPart_, new Guid(reportPart_DataGridView[0, this.reportPart_DataGridView.CurrentCell.RowIndex].Value.ToString()), Int32.Parse(reportPart_DataGridView1[2, this.reportPart_DataGridView.CurrentCell.RowIndex].Value.ToString()));
                        this.reportPartExtendedProperty_TableAdapter1.Fill(this.reportChildDataSet.ReportPartExtendedProperty_);
                    }
                    else
                    {
                        this.reportPart_TableAdapter1.FillBy(this.reportChildDataSet.ReportPart_, ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)), -1);
                        this.reportPartExtendedProperty_TableAdapter1.Fill(this.reportChildDataSet.ReportPartExtendedProperty_);
                    }
                }
            }
        }

        private void reportPart_DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == (this.reportPart_DataGridView1.Columns.Count - 1))
            {
                if (MessageBox.Show("Está seguro que desea eliminar este dictado?", "Información", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    ReportsController.UpdateDictation(new Guid(this.reportPart_DataGridView1[0, e.RowIndex].Value.ToString()), "X");
                refreshView(e.RowIndex);
            }

            if (e.ColumnIndex == (this.reportPart_DataGridView1.Columns.Count - 2))
            {
                if (this.reportPart_DataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() == "A verificar" && this.reportPart_DataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() != "Verificado")
                {
                    Reject Reject = new Reject(new Guid(this.reportPart_DataGridView1[0, e.RowIndex].Value.ToString()), "R");
                    Reject.ShowDialog();
                    refreshView(e.RowIndex);
                }
                else
                    MessageBox.Show(null,"El informe no puede ser rechazado.","Advertencia",MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
            }

            if (e.ColumnIndex == (this.reportPart_DataGridView1.Columns.Count - 3))
            {
                if (this.reportPart_DataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() == "A verificar" && this.reportPart_DataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString() != "Verificado")
                {
                    ReportsController.UpdateDictation(new Guid(this.reportPart_DataGridView1[0, e.RowIndex].Value.ToString()), "V");
                    refreshView(e.RowIndex);
                }
                else
                    MessageBox.Show(null, "El informe no puede ser verificado.", "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        #endregion

        #region Datagrids behavior

        private void reportPart_DataGridView_CellPainting_1(object sender, DataGridViewCellPaintingEventArgs e)
        {
            PaintCellDictations("ColumnDeleteDictation", "deleteD", e);
            PaintCellDictations("ColumnTranscribeDictation", "trancribeD", e);
        }

        private void reportPart_DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            
            PaintCell("ColumnChekedInform", "checkedI", e);

            PaintCell("ColumnRejectedInform", "rejectI", e);

            PaintCell("ColumnDeleteInform", "deleteI", e);
        }

        private void buttonIndependent_Click(object sender, EventArgs e)
        {
            //  reportPart_TableAdapter.Fill(reportDataSet.ReportPart_, new Guid("00000000-0000-0000-0000-000000000000"));
            this.reportPart_TableAdapter1.FillByIndependent(this.reportChildDataSet.ReportPart_, ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));
            typeReport = 1;
        }

        private void refreshView(int y)
        {
            //refrescar el datagridview del los informes
            if (typeReport == 0)
            {
                this.reportPart_TableAdapter1.FillBy(this.reportChildDataSet.ReportPart_, new Guid(reportPart_DataGridView1[14, y].Value.ToString()), Int32.Parse(reportPart_DataGridView1[2, y].Value.ToString()));
                this.reportPartExtendedProperty_TableAdapter1.Fill(this.reportChildDataSet.ReportPartExtendedProperty_);
            }
            else
            {
                this.reportPart_TableAdapter1.FillByIndependent(this.reportChildDataSet.ReportPart_, ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));
            }
        }

        private void RefreshDictations(Guid reportOID)
        {
            reportPart_TableAdapter.Fill(reportDataSet.ReportPart_, reportOID);
        }

        private void PaintCellDictations(string cell, string icon, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && this.reportPart_DataGridView.Columns[e.ColumnIndex].Name == cell && e.RowIndex >= 0)
            {

                e.Paint(e.CellBounds, DataGridViewPaintParts.All);

                DataGridViewButtonCell celBoton = this.reportPart_DataGridView.Rows[e.RowIndex].Cells[cell] as DataGridViewButtonCell;

                if (icon == "trancribeD")
                {
                    
                    Icon tIco = Icon.FromHandle(ViewLayer.Properties.Resources.Edit.GetHicon());
                    e.Graphics.DrawIcon(tIco, e.CellBounds.Left + 3, e.CellBounds.Top + 3);

                    this.reportPart_DataGridView.Rows[e.RowIndex].Height = tIco.Height + 10;
                    this.reportPart_DataGridView.Columns[e.ColumnIndex].Width = tIco.Width + 10;
                    celBoton.ToolTipText = "A Transcribir";

                }

                if (icon == "deleteD")
                {
                    Icon tIco = Icon.FromHandle(ViewLayer.Properties.Resources.Delete.GetHicon());
                    e.Graphics.DrawIcon(tIco, e.CellBounds.Left + 3, e.CellBounds.Top + 3);

                    this.reportPart_DataGridView.Rows[e.RowIndex].Height = tIco.Height + 10;
                    this.reportPart_DataGridView.Columns[e.ColumnIndex].Width = tIco.Width + 10;
                    celBoton.ToolTipText = "Eliminar";
            
                }
                e.Handled = true;
            }
        }

        private void PaintCell(string cell, string icon, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && this.reportPart_DataGridView1.Columns[e.ColumnIndex].Name == cell && e.RowIndex >= 0)
            {
                e.Paint(e.CellBounds, DataGridViewPaintParts.All);

                DataGridViewButtonCell celBoton = this.reportPart_DataGridView1.Rows[e.RowIndex].Cells[cell] as DataGridViewButtonCell;
                if (icon == "deleteI")
                {
                    Icon tIco = Icon.FromHandle(ViewLayer.Properties.Resources.Delete.GetHicon());
                    e.Graphics.DrawIcon(tIco, e.CellBounds.Left + 3, e.CellBounds.Top + 3);
                    this.reportPart_DataGridView1.Rows[e.RowIndex].Height = tIco.Height + 10;
                    this.reportPart_DataGridView1.Columns[e.ColumnIndex].Width = tIco.Width + 10;
                    celBoton.ToolTipText = "Eliminar";
                }

                if (icon == "rejectI")
                {
                    Icon tIco = Icon.FromHandle(ViewLayer.Properties.Resources.DutyRoster.GetHicon());
                    e.Graphics.DrawIcon(tIco, e.CellBounds.Left + 3, e.CellBounds.Top + 3);
                    this.reportPart_DataGridView1.Rows[e.RowIndex].Height = tIco.Height + 10;
                    this.reportPart_DataGridView1.Columns[e.ColumnIndex].Width = tIco.Width + 10;
                    celBoton.ToolTipText = "Rechazar";
                }

                if (icon == "checkedI")
                {
                     Icon tIco = Icon.FromHandle(ViewLayer.Properties.Resources.AcceptCalibration.GetHicon());
                     e.Graphics.DrawIcon(tIco, e.CellBounds.Left + 3, e.CellBounds.Top + 3);
                     this.reportPart_DataGridView1.Rows[e.RowIndex].Height = tIco.Height + 10;
                     this.reportPart_DataGridView1.Columns[e.ColumnIndex].Width = tIco.Width + 10;
                     celBoton.ToolTipText = "Revisado";
                }
                e.Handled = true;
            }
        }

        #endregion

        private void ShowIndependents(object sender, EventArgs e)
        {
            if (this.checkBox1Independent.Checked==true)
            {
                reportPart_TableAdapter.Fill(reportDataSet.ReportPart_, new Guid("00000000-0000-0000-0000-000000000000"));
                this.reportPart_TableAdapter1.FillByIndependent(this.reportChildDataSet.ReportPart_, ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));
                typeReport = 1;
            }
            else 
            {
                this.reportPart_TableAdapter.Fill(this.reportDataSet.ReportPart_, ReportsController.GetReportOIDFromProcedureOID(ReportsController.GetProcedureOIDFromAccessionNumber(MainViewController.currentAccessionNumber)));
                if (reportPart_DataGridView.RowCount != 0)
                {
                    this.reportPart_TableAdapter1.FillBy(this.reportChildDataSet.ReportPart_, new Guid(reportPart_DataGridView[0, 0].Value.ToString()), Int32.Parse(reportPart_DataGridView[2, 0].Value.ToString()));
                }
                typeReport = 0;
            }

        }

        private void ChangeUser(object sender, EventArgs e)
        {  
            if (MainView.MainView.lastTimeLog == 2 && !LoginController.exit && comboBoxUser.Text!=user.getName())
            {
                ControllerLayer.Login.LoginController.exit = false;
                ControllerLayer.Login.LoginController.autentication = false;

                if (InitializationOfLogin2(2, comboBoxUser.SelectedItem.ToString()) == false)
                {
                    comboBoxUser.Text = user.getName();

                }
                else {
                    this.Cursor = Cursors.AppStarting;
                    Environment.SetEnvironmentVariable(ConfigurationManager.AppSettings["UserVariable"].ToString(), user.getName(), EnvironmentVariableTarget.User);
                    MainViewController.nameLabel.Text = "Usuario: " + user.getName();
                    this.Cursor = Cursors.Default;
                }

            }
            ControllerLayer.Login.LoginController.exit =false;
        }
        
        public bool InitializationOfLogin2(int timeLog, string txt)
        {
            while (ControllerLayer.Login.LoginController.exit == false
                && ControllerLayer.Login.LoginController.autentication == false)
            {
                login2 = new Login.LoginView(timeLog, txt);
                if (ControllerLayer.Login.LoginController.exit==false)
                login2.ShowDialog();
            }
            if (ControllerLayer.Login.LoginController.exit == true)
            {
                login2.Close();
                return false;
            }

            if (ControllerLayer.Login.LoginController.autentication == true)
            {
                return true;
            }
            return false;
        }

        private void reportPart_DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                if (reportPart_DataGridView1.SelectedRows[0].Cells[3].Value.ToString() != "Verificado")
                {
                    string currentReportPartOID = reportPart_DataGridView1.SelectedRows[0].Cells[0].Value.ToString();

                    string selectedReport = InformManager.GetPathOfReportPartOID(new System.Guid(currentReportPartOID));
                    string temporaryPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temporaryReport.docx";

                    InformManager.currentDocumentSelection = selectedReport;

                    //using (new Impersonator(ConfigurationManager.AppSettings["ServerUser"].ToString(), ConfigurationManager.AppSettings["ServerName"].ToString(), "MedSoft01"))
                    //{
                    //    File.Copy(selectedReport, temporaryPath, true);
                    //}

                    //ProcessStartInfo documentInfo = new ProcessStartInfo(temporaryPath);

                    //Process genericProcess = new Process();
                    //genericProcess.StartInfo = documentInfo;

                    //genericProcess.EnableRaisingEvents = true;
                    //genericProcess.Exited += new EventHandler(genericProcess_Exited);

                    //genericProcess.Start();
                    //using (new Impersonator(ConfigurationManager.AppSettings["ServerUser"].ToString(), ConfigurationManager.AppSettings["ServerName"].ToString(), "MedSoft01"))
                    //{
                        DocumentLayer.DocumentManager.OpenDocument(selectedReport);
                    //}
                }
                else
                {
                    string currentReportPartOID = reportPart_DataGridView1.SelectedRows[0].Cells[0].Value.ToString();

                    string selectedReport = InformManager.GetPathOfReportPartOID(new System.Guid(currentReportPartOID));

                    //using (new Impersonator(ConfigurationManager.AppSettings["ServerUser"].ToString(), ConfigurationManager.AppSettings["ServerName"].ToString(), "MedSoft01"))
                    //{
                        File.Copy(selectedReport, Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temporaryDocument.docx", true);
                    //}
                    InformManager.ConvertDocxToPdf(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temporaryDocument.docx");
                    File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temporaryDocument.docx");
                    //Abrir pdf.
                    Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temporaryDocument.pdf");
                }
            }
        }

        void genericProcess_Exited(object sender, EventArgs e)
        {
            string temporaryPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\temporaryReport.docx";

            //using (new Impersonator(ConfigurationManager.AppSettings["ServerUser"].ToString(), ConfigurationManager.AppSettings["ServerName"].ToString(), "MedSoft01"))
            //{
                File.Copy(temporaryPath, InformManager.currentDocumentSelection, true);
            //}
            File.Delete(temporaryPath);
        }

        private void buttonViewStudy_Click(object sender, EventArgs e)
        {
            try
            {
                CCWServiceController c = new CCWServiceController();
                if (c.openStudyAtWorkstation(MainViewController.currentAccessionNumber) == false)
                {
                    MessageBox.Show("No se encuentra la imagen correspondiente al estudio.");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("El Workstation no se encuentra activo. Inicie la aplicación para continuar.");
            }
        }
    }
}
